layui.use(['util'], function (util) {

    var
        table = util.table,//table
        form = util.form, //form
        layer = util.layer;//layer


    var attrs = {

        constants: {
            html: {
                editSubAttrs: appUrl + "/resources/js/lib/attrs/editSubAttrs.html",
                edit: appUrl + "/resources/js/lib/attrs/editAttrs.html"
            },
            api: {
                edit: appUrl + "/attrs/edit",
                editSub: appUrl + "/attrs/editSub",
                del: appUrl + "/attrs/del",
                delSub: appUrl + "/attrs/delSub",
                add: appUrl + "/attrs/add",
                addSub: appUrl + "/attrs/addSub",
                queryAttrs: appUrl + '/attrs/queryAttrsList'
            }
        },

        init: function () {
            this.renderPage()
        },

        renderPage: function () {
            var self = this;
            //执行一个 table 实例
            table.render({
                elem: '#attrsTable'
                , height: 800
                , url: self.constants.api.queryAttrs//数据接口
                , method: 'post' //如果无需自定义HTTP类型，可不加该参数
                , title: '用户表'
                , page: true //开启分页
                , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
                , totalRow: true //开启合计行
                , data: []//开启合计行
                , cols: [[ //表头
                    {type: 'checkbox'},
                    {
                        field: 'id',
                        title: '属性列表', width: '20%',
                        templet: function () {
                            return '<a lay-event="addRowTable"><i class="layui-icon layui-icon-triangle-r"></i></a>'
                        }
                    }
                    , {field: 'name', title: '类别名称', width: '40%'}
                    , {title: '启用状态', width: '20%', align: 'center', templet: '#attrsStatusBar'}
                    , {title: '操作', width: '20%', align: 'center', toolbar: '#attrsTableBar'}
                ]]
            });

            //监听头工具栏事件
            table.on('toolbar(attrsFilter)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id)
                    , data = checkStatus.data; //获取选中的数据
                switch (obj.event) {
                    case 'add':
                        self.add(obj.data || {});
                        break;
                    case 'update':
                        if (data.length === 0) {
                            layer.msg('请选择一行');
                        } else if (data.length > 1) {
                            layer.msg('只能同时编辑一个');
                        } else {
                            self.edit(data);
                        }
                        break;
                    case 'delete':
                        if (data.length === 0) {
                            layer.msg('请选择一行');
                        } else {
                            layer.confirm('真的删除行么', function (index) {
                                obj.del(); //删除对应行（tr）的DOM结构
                                layer.close(index);
                                self.del(data);
                            });
                        }
                        break;
                }
            });

            //监听行工具事件
            table.on('tool(attrsFilter)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                var data = obj.data //获得当前行数据
                    , layEvent = obj.event //获得 lay-event 对应的值
                    , $this = $(this)
                    , tr = $this.parents('tr');
                var trIndex = tr.data('index');
                if (layEvent === 'addSub') {
                    self.addSub(data);
                } else if (layEvent === 'del') {
                    layer.confirm('真的删除行么', function (index) {
                        obj.del(); //删除对应行（tr）的DOM结构
                        layer.close(index);
                        self.del(data);
                    });
                } else if (layEvent === 'edit') {
                    self.edit(data);
                } else if (layEvent === 'addRowTable') {
                    $(this).attr('lay-event', 'fold').html('<i class="layui-icon layui-icon-triangle-d"></i>');
                    var tableId = 'tableOut_tableIn_' + trIndex;
                    var _html = [
                        '<tr class="table-item">',
                        '<td colspan="' + tr.find('td').length + '" style="padding: 10px 15px;">',
                        '<table id="' + tableId + '" lay-filter="attrsSubFilter"></table>',
                        '</td>',
                        '</tr>'
                    ];
                    tr.after(_html.join('\n'));
                    // 渲染table
                    table.render({
                        elem: '#' + tableId,
                        data: data.goodAttributes || []
                        , page: true //开启分页
                        , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档,
                        , cols: [[
                            {type: 'checkbox'},
                            {field: 'name', title: '属性名称'},
                            {field: 'inputType', title: '是否启用', align: 'center', toolbar: '#attrsSubStatusBar'},
                            {title: '操作', align: 'center', toolbar: '#attrsSubTableBar'}
                        ]]
                    });

                    table.on('tool(attrsSubFilter)', function (obj) {
                        var laySubEvent = obj.event;
                        var subObjData = obj.data;
                        switch (laySubEvent) {
                            case 'delSub':
                                layer.confirm('真的删除行么', function (index) {
                                    obj.del(); //删除对应行（tr）的DOM结构
                                    layer.close(index);
                                    self.delSub(subObjData);
                                });
                                break;
                            case 'editSub':
                                self.editSub(subObjData,obj);
                                break;
                        }
                    })
                } else if (layEvent === 'fold') {
                    $(this).attr('lay-event', 'addRowTable').html('<i class="layui-icon layui-icon-triangle-r"></i>');
                    tr.next().remove();
                }
            });
        },
        edit: function (data) {
            var self = this;

            util.templateProxy(self.constants.html.edit, data,
                {
                    title: '编辑类目',
                    success: function () {
                        form.val("attrEdit", data);
                        form.render();
                    },
                    confirm: function (formData) {
                        formData.enabled = formData.enabled === 'on';
                        util.post(self.constants.api.edit, formData, function (resp) {
                            if (resp && resp.success) {
                                layer.closeAll();
                                self.renderPage();
                            }
                        })
                    },
                    cancel: function () {
                        layer.closeAll();
                    }
                })
        },
        addSub: function (data) {
            var self = this;

            var parentData = {
                attributeCategoryId: data.id || '',
                inputType: true
            };
            util.templateProxy(self.constants.html.editSubAttrs, parentData,
                {
                    title: '添加子属性',
                    success: function () {
                        form.val("editSub", parentData);
                        form.render();
                    },
                    confirm: function (formData) {
                        util.post(self.constants.api.addSub, formData, function (resp) {
                            if (resp && resp.success) {
                                layer.closeAll();
                                self.renderPage();
                            }
                        })
                    },
                    cancel: function () {
                        layer.closeAll();
                    }
                })
        },
        editSub: function (data,obj) {
            var self = this;

            util.templateProxy(self.constants.html.editSubAttrs, data,
                {
                    title: '编辑属性',
                    success: function () {
                        form.val("editSub", data);
                        form.render();
                    },
                    confirm: function (formData) {
                        formData.inputType = formData.inputType === 'on';
                        formData.value = formData.value || '';
                        util.post(self.constants.api.editSub, formData, function (resp) {
                            if (resp && resp.success) {
                                layer.closeAll();
                                formData.inputType = formData.inputType? "<div class=\"ayui-bg-green\">已启用</div>":"<div class=\"layui-bg-red\">已禁用</div>";
                                obj.update(formData)
                            }
                        })
                    },
                    cancel: function () {
                        layer.closeAll();
                    }
                })
        },
        add: function (data) {
            var self = this;
            util.templateProxy(self.constants.html.edit, data,
                {
                    title: '添加类目',
                    success: function () {
                        form.val("edit", data);
                        form.render();
                    },
                    confirm: function (formData) {
                        util.post(self.constants.api.add, formData, function (resp) {
                            if (resp && resp.success) {
                                layer.closeAll();
                                self.renderPage();
                            }
                        })
                    },
                    cancel: function () {
                        layer.closeAll();
                    }
                })
        },

        del: function (data) {
            util.post(this.constants.api.del, {id: data.id}, function () {
                layer.closeAll();
            });
        },
        delSub: function (data) {
            util.post(this.constants.api.delSub, {id: data.id}, function () {
                layer.closeAll();
            });
        }

    };

    attrs.init();
});